package com.ld.rightsSystem.filter;

import com.alibaba.fastjson.JSONObject;
import com.ld.rightsSystem.Enum.ResponseEnum;
import com.ld.rightsSystem.mapper.TUserRepository;
import com.ld.rightsSystem.utils.JwtUtil;
import com.ld.rightsSystem.vo.R;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一获取token中的userName
 */
@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    public static ThreadLocal<String> userNameThreadLocal = new ThreadLocal<>();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        if(!request.getRequestURI().equals("/admin/sys-user/login")){
            final String requestTokenHeader = request.getHeader("Authorization");
            String username = null;
            String jwtToken = null;
            try{
                jwtToken = requestTokenHeader.substring(7);
                username = jwtUtil.getUsernameFromToken(jwtToken);
                userNameThreadLocal.set(username);
            }catch (Exception e) {
//                throw new JwtException("get username from token error");
                logger.error("get username from token error");
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "*");
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(200);
                R error = new R().error(ResponseEnum.UNAUTHORIZED, null);
                response.getWriter().write(JSONObject.toJSONString(error));
                return;
            }
        }
        chain.doFilter(request, response);
    }
}

